import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class DualAxisWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建一个figure和axes
        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.ax1 = self.fig.add_subplot(111)
        self.ax2 = self.ax1.twinx()  # 创建第二个Y轴

        # 绘制数据
        x = range(1, 11)
        y1 = [i ** 2 for i in x]
        y2 = [i ** 3 for i in x]

        # 绘制线条
        line1, = self.ax1.plot(x, y1, 'g-', label='Y1 Squared')
        line2, = self.ax2.plot(x, y2, 'b-', label='Y2 Cubed')

        # 创建左Y轴的图例
        ax1_legend = self.ax1.legend(handles=[line1], labels=['Y1 Squared'], loc='upper left',
                                     bbox_to_anchor=(0.01, 0.9), borderaxespad=0.)
        # 将图例添加到axes，但不会显示边框和背景
        self.ax1.add_artist(ax1_legend)

        # 创建右Y轴的图例
        ax2_legend = self.ax2.legend(handles=[line2], labels=['Y2 Cubed'], loc='upper right',
                                     bbox_to_anchor=(0.99, 0.9), borderaxespad=0.)
        # 将图例添加到axes，但不会显示边框和背景
        self.ax2.add_artist(ax2_legend)

        # 设置Y轴标签
        self.ax1.set_ylabel('Y1', color='g')
        self.ax2.set_ylabel('Y2', color='b')

        # 设置X轴标签
        self.ax1.set_xlabel('X')

        # 创建canvas
        self.canvas = FigureCanvas(self.fig)

        # 设置窗口布局
        self.setCentralWidget(self.canvas)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWin = DualAxisWindow()
    mainWin.show()
    sys.exit(app.exec_())